package co.fitstart.weapp.api.web.controller.coach;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.result.HttpResult;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.courseware.assessment.BasicData;
import co.fitstart.entity.courseware.assessment.PostureJoint;
import co.fitstart.entity.courseware.assessment.StudentAssessment;
import co.fitstart.entity.principal.Principal;
import co.fitstart.weapp.api.entity.StudentAssessmentRequest;
import co.fitstart.weapp.api.service.CoachService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CoursewareService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/coach/course-rounds/{courseRoundId}")
public class StudentAssessmentController {

    private static final Logger logger = LoggerFactory.getLogger(StudentAssessmentController.class);

    @Autowired
    private CoachService coachService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CoursewareService coursewareService;

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/assessment", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult loadLatest(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            StudentAssessment studentAssessment = coursewareService.loadStudentAssessment(courseRound);
            
            if(studentAssessment == null) {
                BasicData basicData = coursewareService.loadBasicData(courseRound);
                PostureJoint postureJoint = coursewareService.loadPostureJoint(courseRound);
                
                httpResult.success().message("获取数据成功")
                                    .data("basicData", basicData)
                                    .data("postureJoint", postureJoint)
                                    .data("showRecord", false)
                                    .data("isMainCoach", coach == courseRound.getCoach());
            } else {
                httpResult.success().message("获取数据成功")
                                    .data("basicData", studentAssessment.getBasicData())
                                    .data("postureJoint", studentAssessment.getPostureJoint())
                                    .data("showRecord", true)
                                    .data("isMainCoach", coach == courseRound.getCoach());
            }
        } catch (Exception e) {
            logger.error("#StudentAssessmentController# loadLatest() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "/assessments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult list(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            List<StudentAssessment> studentAssessments = coursewareService.listStudentAssessment(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("assessments", studentAssessments);
        } catch (Exception e) {
            logger.error("#StudentAssessmentController# list() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param assessmentId
     * @return
     */
    @RequestMapping(value = "/assessments/{assessmentId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult view(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId,
                           @PathVariable("assessmentId") Long assessmentId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            StudentAssessment studentAssessment = coursewareService.loadStudentAssessment(assessmentId);
            
            httpResult.success().message("获取数据成功")
                                .data("basicData", studentAssessment.getBasicData())
                                .data("postureJoint", studentAssessment.getPostureJoint())
                                .data("showRecord", true)
                                .data("isMainCoach", coach == courseRound.getCoach());
        } catch (Exception e) {
            logger.error("#StudentAssessmentController# view() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param basicData
     * @param postureJoint
     * @param map
     * @return
     */
    @RequestMapping(value = "/assessments", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult create(@RequestParam("mobile") String mobile,
                             @PathVariable("courseRoundId") Long courseRoundId,
                             @RequestBody StudentAssessmentRequest request) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            if(coach == courseRound.getCoach()) {
                coursewareService.createStudentAssessment(courseRound, request.getBasicData(), request.getPostureJoint());
            } else {
                httpResult.fail("500").message("你不是主教练，不能创建新评估");
            }
            
            httpResult.success().message("创建新评估成功");
        } catch (Exception e) {
            logger.error("#StudentAssessmentController# create() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }
}
